<?php
if ( !defined('IN_ADMINCP') || !defined('IN_SEC') ){
	exit('Access Denied.');
}

$id = intval(trim($_G['gp_id']));
$companyid = abs(intval($_G['gp_companyid']));
$departmentid = abs(intval($_G['gp_departmentid']));

$maxlv = (int)$admincp->admin['group']['rank']-1;
//如果传入$id，检测分组是否存在，不存在提示错误
if ( $id ){
	if ( !$group = fetch('admincp_group', $id) ){
		$group->cpmsg('管理组不存在');
	}
	//如果存在管理组，编辑菜单
	$admincp->editmenu('editgroup', '编辑管理组');
		//禁止编辑系统最高管理组
	if ( $group['id'] == 1 ){
		$admincp->cpmsg('禁止编辑系统最高管理组');
	}
	if ( $admincp->admin['group']['rank'] < $group['rank'] ){
		//禁止编辑等级比自己高的管理组
		$admincp->cpmsg('您的等级无法更改该管理组' . $admincp->admin['group']['rank']);
	}
	$gact = json_decode($group['action'] == 'all' ? '' : $group['action'], true);
}

$companys = limitquery('companys');

$departments = limitquery('admincp_department');
$where = array();
$where['departmentid'] = 0;

if( $group['departmentid'] ){
	unset($where['departmentid']);
	$where[] = "`departmentid` = 0 OR `departmentid` = {$group['departmentid']}";
}

if( $departmentid ){
	unset($where['departmentid']);
	$where[] = "`departmentid` = 0 OR `departmentid` = {$departmentid}";
}
$groups = limitquery('admincp_group', $where);

$actions = &$admincp->actions;

if ( is_post() ){
	if( !confirm_password($admincp->admin) ){
		$admincp->cpmsg('密码不正确！授权操作失败！');
	}

	$actions = parse_array($actions, 'name');
	$operation = $_G['gp_opt'];
	$name = $_G['gp_name'] ? htmlspecialchars($_G['gp_name']) : $admincp->cpmsg('请输入职位名称');
	$rank = $_G['gp_rank'] ? intval($_G['gp_rank']) : $admincp->cpmsg('请输入等级');
	$rank = ($rank < $admincp->admin['group']['rank']) ? $rank : $admincp->cpmsg('您的等级不足以完成本次操作');

	$departmentid = $_G['gp_departmentid'] ? abs(intval($_G['gp_departmentid'])) : 0;
	$parentid = $_G['gp_parentid'] ? abs(intval($_G['gp_parentid'])) : 0;

	if ( $exists = fetch('admincp_group', $name, 'name') ){
		if( $group ){
			if ( $group['name'] != $exists['name'] ){
				$admincp->cpmsg('该分组已经存在');
			}
		}else{
			$admincp->cpmsg('该分组已经存在');
		}
	}

	$json = array();

	foreach( $actions as $k => $v ){
		if ( $v['mixed'] && !$operation[$k] ){
			$admincp->cpmsg($v . '选择受限！');
		}
	}

	foreach( $operation as $k => $v ){
		if ( !$actions[$k] ){
			$admincp->cpmsg($k . ':授权限制！');
		}else{
			foreach( $v as $subkey => $sub ){
				if ( !$actions[$k]['submenu'][$sub] ){
					$admincp->cpmsg($k . ':' . $sub . ':授权限制！');
				}else{
					$json[$k][$sub] = $subkey;
				}
			}
		}
	}
	$action = json_encode($json);

	$update = array(
		'name' => $name,
		'rank' => $rank,
		'action' => $action,
		'departmentid' => $departmentid,
		'parentid' => $parentid
	);

	if ( $group ){
		update('admincp_group', $group['id'], $update);
	}else{
		DB::Insert('admincp_group', $update);
	}
	$admincp->success();
}

?>